/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FindReplace.java
 *
 * Created on 13.Haz.2009, 13:14:38
 */

package com.meraklisina.latexeditor;

import java.awt.event.KeyListener;

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextPane;

import com.meraklisina.latexeditor.mdi.TextEditor.TextEditors;

/**
 *
 * @author eozkanal
 */
public class FindReplace extends javax.swing.JPanel implements KeyListener {
	private JTextPane textEditor;
	private JDialog dialog;
	private JTabbedPane tab_Editors;
	/** Creates new form FindReplace */
	public FindReplace(JDialog jd, JTabbedPane editors) {
		this.dialog=jd;
		this.tab_Editors=editors;

		this.setFocusable(true);
		this.addKeyListener(this);

		initComponents();

		TxtFind.addKeyListener(this);
		TxtReplace.addKeyListener(this);
		BtnFindNext.addKeyListener(this);
		BtnReplace.addKeyListener(this);
		BtnReplaceAll.addKeyListener(this);
		BtnCancel.addKeyListener(this);
		RBUp.addKeyListener(this);
		RBDown.addKeyListener(this);
	}

	/** Returns active JTextPane object
	 */
	public JTextPane getTextEditor()
	{
		return new TextEditors().GetJTextPaneAt(this.tab_Editors, this.tab_Editors.getSelectedIndex());
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		BGDirection = new javax.swing.ButtonGroup();
		BtnFindNext = new javax.swing.JButton();
		BtnReplace = new javax.swing.JButton();
		BtnReplaceAll = new javax.swing.JButton();
		BtnCancel = new javax.swing.JButton();
		TxtFind = new javax.swing.JTextField();
		jLabel1 = new javax.swing.JLabel();
		jLabel2 = new javax.swing.JLabel();
		TxtReplace = new javax.swing.JTextField();
		jLabel3 = new javax.swing.JLabel();
		RBUp = new javax.swing.JRadioButton();
		RBDown = new javax.swing.JRadioButton();

		addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				formKeyPressed(evt);
			}
		});

		BtnFindNext.setText("Find Next");
		BtnFindNext.setToolTipText("Find Next");
		BtnFindNext.setName("Find Next"); // NOI18N
		BtnFindNext.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				BtnFindNextActionPerformed(evt);
			}
		});

		BtnReplace.setText("Replace");
		BtnReplace.setToolTipText("Replace");
		BtnReplace.setName("BtnReplace"); // NOI18N
		BtnReplace.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				BtnReplaceActionPerformed(evt);
			}
		});

		BtnReplaceAll.setText("Replace All");
		BtnReplaceAll.setToolTipText("Replace All");
		BtnReplaceAll.setName("BtnReplaceAll"); // NOI18N
		BtnReplaceAll.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				BtnReplaceAllActionPerformed(evt);
			}
		});

		BtnCancel.setText("Cancel");
		BtnCancel.setToolTipText("Cancel");
		BtnCancel.setName("BtnCancel"); // NOI18N
		BtnCancel.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				BtnCancelActionPerformed(evt);
			}
		});

		TxtFind.setName("TxtFind"); // NOI18N

		jLabel1.setText("Find What:");
		jLabel1.setName("jLabel1"); // NOI18N

		jLabel2.setText("Replace With:");
		jLabel2.setName("jLabel2"); // NOI18N

		TxtReplace.setName("TxtReplace"); // NOI18N

		jLabel3.setText("Direction");
		jLabel3.setName("jLabel3"); // NOI18N

		BGDirection.add(RBUp);
		RBUp.setText("Up");
		RBUp.setToolTipText("Up");
		RBUp.setName("RBUp"); // NOI18N
		RBUp.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				RBUpActionPerformed(evt);
			}
		});

		BGDirection.add(RBDown);
		RBDown.setSelected(true);
		RBDown.setText("Down");
		RBDown.setToolTipText("Down");
		RBDown.setName("RBDown"); // NOI18N

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
		this.setLayout(layout);
		layout.setHorizontalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addComponent(jLabel1)
								.addComponent(jLabel2)
								.addComponent(jLabel3))
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
										.addGroup(layout.createSequentialGroup()
												.addComponent(RBUp)
												.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
												.addComponent(RBDown))
												.addComponent(TxtReplace, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
												.addComponent(TxtFind, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE))
												.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
												.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
														.addComponent(BtnCancel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
														.addComponent(BtnReplaceAll, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
														.addComponent(BtnReplace, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
														.addComponent(BtnFindNext, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
														.addContainerGap())
		);
		layout.setVerticalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(BtnFindNext)
								.addComponent(TxtFind, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(jLabel1))
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
										.addComponent(BtnReplace)
										.addComponent(jLabel2)
										.addComponent(TxtReplace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addGroup(layout.createSequentialGroup()
														.addComponent(BtnReplaceAll)
														.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
														.addComponent(BtnCancel))
														.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
																.addComponent(jLabel3)
																.addComponent(RBDown)
																.addComponent(RBUp)))
																.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
	}// </editor-fold>//GEN-END:initComponents

	/** Searchs text entered at active editor tab and selects it. If cannot found displays
	 * a message box
	 */
    private boolean find()
    {
        int index;
        String newLine = "\r\n";//CU.defining new line as a variable
        int newLineIndex = 0;//CU.initializing new line
        int newLineCount = 0;//CU.initializing new line

        if(RBDown.isSelected())
        {	
            index=getTextEditor().getText().indexOf(TxtFind.getText(), getTextEditor().getCaretPosition());
            
            //System.out.println("1 - TxtFind.getText(): " + TxtFind.getText());
            //System.out.println("1 - getTextEditor().getText() :" + getTextEditor().getText());
            //System.out.println("1 - getTextEditor().getCaretPosition() :" + getTextEditor().getCaretPosition());
            //System.out.println("1 - index :" + index); 
        
            if(index!=-1) //CU.if text is not found
            {
            	newLineIndex = getTextEditor().getText().indexOf(newLine, newLineIndex);
            	
            	if (newLineIndex != -1)//CU.if a new line is found
            		newLineIndex++;
            	
            	while(!(newLineIndex > index || newLineIndex == -1))//CU.finding the number of newLines from the start point to the index
            	{
                	//System.out.println("newLineIndex:" + newLineIndex);
                	newLineCount++;
                	newLineIndex = getTextEditor().getText().indexOf(newLine, newLineIndex);
                	if (newLineIndex != -1)
                		newLineIndex++;	
                }
            	//System.out.println("found - Index: " + index);
                index = index - newLineCount;//CU.decreasing the position 
            }
        }
        else
        {	newLineIndex = 0;//CU.initializing new line for each request
        	index=getTextEditor().getText().lastIndexOf(TxtFind.getText(), getTextEditor().getCaretPosition());
               		
            //System.out.println("2 - TxtFind.getText(): " + TxtFind.getText());
            //System.out.println("2 - getTextEditor().getText() " + getTextEditor().getText());
            //System.out.println("2 - getTextEditor().getCaretPosition() " + getTextEditor().getCaretPosition());//CU.tracking positions and index            
            //System.out.println("2 - index :" + index); 
            
            if(  index>=getTextEditor().getSelectionStart())
            	index--;
            
            if(index!=-1) //CU.if text is not found
            {
            	newLineIndex = getTextEditor().getText().indexOf(newLine, newLineIndex);
            	
            	if (newLineIndex != -1)//CU.if a new line is found
            		newLineIndex++;
            	
            	while(!(newLineIndex > index || newLineIndex == -1))//CU.finding the number of newLines from the start point to the index
            	{
                	//System.out.println("newLineIndex:" + newLineIndex);
                	newLineCount++;
                	newLineIndex = getTextEditor().getText().indexOf(newLine, newLineIndex);
                	if (newLineIndex != -1)
                		newLineIndex++;	
                }
            	//System.out.println("found - Index: " + index);
                index = index - newLineCount;//CU.decreasing the position 
            }
        }
  
        if(index!=-1)
        {
        
            getTextEditor().setCaretPosition(index);
            getTextEditor().setSelectionStart(index);
            getTextEditor().setSelectionEnd(index + TxtFind.getText().length());

            return true;
        }
        else
        {
            JOptionPane.showMessageDialog(this, "Text not found", "Find", 1);

            return false;
        }
    }

	/** Searchs text entered at active editor and replaces it with replace text. If cannot found find text displays
	 * a message box
	 */
	private void replace()
	{
		if(getTextEditor().getSelectedText()!=null)
		{
			if(getTextEditor().getSelectedText().equals(TxtFind.getText()))
			{
				getTextEditor().replaceSelection(TxtReplace.getText());
				getTextEditor().setSelectionStart(getTextEditor().getSelectionStart() - TxtReplace.getText().length());
				getTextEditor().setSelectionEnd(getTextEditor().getSelectionStart() + TxtReplace.getText().length());
			}
			else
			{
				if(find())
					replace();
			}
		}
		else
		{
			if(find())
				replace();
		}
	}

	private void BtnFindNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnFindNextActionPerformed
		// TODO add your handling code here:
		find();
	}//GEN-LAST:event_BtnFindNextActionPerformed

	private void BtnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnCancelActionPerformed
		// TODO add your handling code here:
		this.dialog.setVisible(false);
	}//GEN-LAST:event_BtnCancelActionPerformed

	private void RBUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RBUpActionPerformed
		// TODO add your handling code here:
	}//GEN-LAST:event_RBUpActionPerformed

	public void keyPressed(java.awt.event.KeyEvent evt)
	{
		if(evt.getKeyCode()==evt.VK_ESCAPE)
			this.dialog.setVisible(false);
	}
	public void keyTyped(java.awt.event.KeyEvent ke){}
	public void keyReleased(java.awt.event.KeyEvent ke){}

	private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
		// TODO add your handling code here:
	}//GEN-LAST:event_formKeyPressed

	private void BtnReplaceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnReplaceActionPerformed
		// TODO add your handling code here:

		replace();
	}//GEN-LAST:event_BtnReplaceActionPerformed

	private void BtnReplaceAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnReplaceAllActionPerformed
		// TODO add your handling code here:
		getTextEditor().setText(getTextEditor().getText().replaceAll(TxtFind.getText(), TxtReplace.getText()));
	}//GEN-LAST:event_BtnReplaceAllActionPerformed


	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.ButtonGroup BGDirection;
	private javax.swing.JButton BtnCancel;
	private javax.swing.JButton BtnFindNext;
	private javax.swing.JButton BtnReplace;
	private javax.swing.JButton BtnReplaceAll;
	private javax.swing.JRadioButton RBDown;
	private javax.swing.JRadioButton RBUp;
	private javax.swing.JTextField TxtFind;
	private javax.swing.JTextField TxtReplace;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	// End of variables declaration//GEN-END:variables

}
